package controller

import (
	"asuOfficialApi/comm"
	"asuOfficialApi/model"
	"asuOfficialApi/service"
	"asuOfficialApi/vo"
	"asuOfficialApi/web/middleware"
	"github.com/kataras/iris"
	"gopkg.in/go-playground/validator.v9"
	"log"
)

type UserController struct {
	Ctx          iris.Context
	ServiceUser  service.UserService
	ServiceToken service.TokenService
}

// http://localhost:8080/v1/anno/register
func (c *UserController) PostAnnoRegister() iris.Map {
	var userForm = &vo.UserForm{
		Username: c.Ctx.PostValue("username"),
		Password: c.Ctx.PostValue("password"),
	}
	if err := middleware.ValidateStruct(userForm); err != nil {
		if errs, ok := err.(validator.ValidationErrors); ok {
			return comm.Fail(comm.ErrorParamFormat, errs[0].Translate(middleware.Translate()))
		}
	}

	if user, err := c.ServiceUser.Register(userForm.Username, userForm.Password); err != nil {
		return comm.Fail(err.Code, err.Error.Error())
	} else {
		data := map[string]interface{}{"user_id": user.Id}
		return comm.Success(data)
	}
}

// http://localhost:8080/v1/anno/login
func (c *UserController) PostAnnoLogin() iris.Map {
	var userForm = &vo.UserForm{
		Username: c.Ctx.PostValue("username"),
		Password: c.Ctx.PostValue("password"),
	}
	if err := middleware.ValidateStruct(userForm); err != nil {
		if errs, ok := err.(validator.ValidationErrors); ok {
			return comm.Fail(comm.ErrorParamFormat, errs[0].Translate(middleware.Translate()))
		}
	}

	if user, err := c.ServiceUser.Login(userForm.Username, userForm.Password); err != nil {
		return comm.Fail(err.Code, err.Error.Error())
	} else {
		var token string
		tokenModel := c.ServiceToken.GetTokenById(user.Id)
		log.Println("model is ", tokenModel)
		if tokenModel != nil && tokenModel.Id > 0 {
			token = tokenModel.Token
		} else {
			tokenModel := c.ServiceToken.Insert(user.Id, model.TokenUserTypeUser)
			token = tokenModel.Token
		}

		// 设置到cookie里面
		loginUser := vo.LoginUser{
			Uid:      user.Id,
			Username: user.Username,
			Now:      comm.NowUnix(),
			Token:    token,
			Ip:       comm.ClientIP(c.Ctx.Request()),
		}
		comm.SetLoginUser(c.Ctx.ResponseWriter(), &loginUser)

		data := map[string]interface{}{"user": user, "token": token}
		return comm.Success(data)
	}
}

func (c *UserController) GetUser() iris.Map {
	loginUser := comm.GetLoginUser(c.Ctx.Request())
	if user, e := c.ServiceUser.FindById(loginUser.Uid); e != nil {
		return comm.Fail(e.Code, e.Error.Error())
	} else {
		data := map[string]interface{}{"user": user}
		return comm.Success(data)
	}
}

func (c *UserController) PostLogout() iris.Map {
	loginUser := comm.GetLoginUser(c.Ctx.Request())
	err := c.ServiceToken.DeleteToken(loginUser.Token)
	if err != nil {
		return comm.Fail(err.Code, err.Error.Error())
	}

	comm.SetLoginUser(c.Ctx.ResponseWriter(), nil)
	return comm.Success("token删除成功")
}
